package com.aaa.sso.util;

import com.aaa.common.bo.User;
import com.aaa.common.util.Result;
import com.aaa.sso.service.RemoteUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * @author Xiujie Yu
 * @Date 2021-01-21
 * @Time 16:48
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    private RemoteUserService remoteUserService;
    /**
     * 功能描述:授权方法
     * @param principalCollection PrincipalCollection
     * @return org.apache.shiro.authz.AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 功能描述:认证方法
     * @param authenticationToken AuthenticationToken
     * @return org.apache.shiro.authc.AuthenticationInfo
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String userName = (String) authenticationToken.getPrincipal();
        //调用远程方法，获取用户信息
        Result<User> result = remoteUserService.getUserByUserName(userName);
        User user = result.getT();
        if (user==null){
            //用户不存在
            throw new AccountException();
        }
        return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),"");
    }


}
